﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NBusiness.CodeDom;
using Microsoft.VisualStudio.OLE.Interop;
using EnvDTE;
using NBusiness.ESharp.Compiler;
using NBusiness.ESharp;
using System.IO;
using NBusiness.CodeDom.Compiler;
using System.Reflection;
using System.Security.Cryptography;

namespace NBusiness.VisualStudio
{
    internal static class Extensions
    {
        public static EntityFile[] GetESharpProjectItems(this ProjectItem item)
        {
            List<EntityFile> items = new List<EntityFile>();
            if (Path.GetExtension(item.Name) == ".es")
            {
                string text;
                if (item.IsDirty)
                {
                    text = item.Document.ReadAllText();
                }
                else text = File.ReadAllText(item.Document.FullName);

                EntityFile file = new EntityFile { FileName = item.Document.FullName, Data = text };
                items.Add(file);
            }

            if (item.ProjectItems.Count > 0)
            {
                foreach (ProjectItem i in item.ProjectItems)
                    items.AddRange(GetESharpProjectItems(i));
            }
            return items.ToArray();
        }

        public static string ReadAllText(this Document document)
        {
            TextDocument doc = document.Object("TextDocument") as TextDocument;
            EditPoint startPoint = doc.StartPoint.CreateEditPoint();
            EditPoint endPoint = doc.EndPoint.CreateEditPoint();
            return startPoint.GetText(endPoint);
        }

        public static string ReadAllText(this Window window)
        {
            OutputWindow oWin = window.Object as OutputWindow;
            TextSelection selection = oWin.ActivePane.TextDocument.Selection;
            
            TextPoint oldAnchor, oldActive;
            oldAnchor = selection.AnchorPoint.CreateEditPoint();
            oldActive = selection.ActivePoint.CreateEditPoint();

            selection.SelectAll();
            string outputText = selection.Text;

            selection.MoveToAbsoluteOffset(oldAnchor.AbsoluteCharOffset, false); //set active point
            selection.SwapAnchor(); //set anchor to active point
            selection.MoveToAbsoluteOffset(oldActive.AbsoluteCharOffset, true);

            return outputText;
        }
    }
}
